import 'dart:io';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;

class pdfUtils {
  Future<String> saveImgeToPdf(List<String> source) async {
    int indexPoint = source[0].indexOf('.');
    // 保存PDF到文件
    String fileName = source[0].substring(0, indexPoint) + '_pre.pdf';
    final pdf = pw.Document();

    // 2. 遍历所有图片URL
    for (int i = 0; i < source.length; i++) {
      final url = source[i];

      // 将图片添加到PDF
      pdf.addPage(
        pw.Page(
          build: (pw.Context context) {
            return pw.Center(
              child: pw.Image(
                // pw.MemoryImage(response.data),
                pw.MemoryImage(File(url).readAsBytesSync()),
                fit: pw.BoxFit.contain,
              ),
            );
          },
          pageFormat: PdfPageFormat.a4, // 设置为A4格式
        ),
      );
    }
    // 保存PDF文件
    final fileTemp = File(fileName);
    await fileTemp.writeAsBytes(await pdf.save());
    return fileName;
  }
}
